import axios from 'axios'
import store from '@/store'
import router from '@/router'

const service = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = store.state.user.token
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => response.data,
    error => {
        if (error.response && error.response.status === 401) {
            // token 过期或无效
            store.dispatch('user/logout')
            router.push('/login')
        }
        return Promise.reject(error)
    }
)

export default service 